import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-algorithm-order',
  templateUrl: './algorithm-order.component.html',
  styleUrls: ['./algorithm-order.css']
})
export class AlgorithmOrderComponent {
  queryForm = {
    companyId: '',
    loadingTimeType: '',
    unLoadingTimeType: '',
    dateType: '1',
    startTime: '',
    endTime: '',
    sortType: '',
    sortTypeNameArr: [],
    deviceId: '',
    useTypeL2: ''
  }
  dateNumber: any = '10'
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  activeSelected: string = '' //row高亮
  startTime: string = '' //开始时间
  endTime: string = '' //结束时间

  transformIcon = require('./icon/transform.png') // 交换装卸货地图标
  areaData = [] // 获取的地区信息
  provinceNameArr = [] // 第一个省选择框对应的数组
  cityNameArr = [] // 第一个市选择框对应的数组
  townNameArr = [] // 第一个区选择框对应的数组

  provinceNameArr1 = [] // 第二个省选择框对应的数组
  cityNameArr1 = [] // 第二个市选择框对应的数组
  townNameArr1 = [] // 第一个区选择框对应的数组

  areaSelected = {
    loadingAddressPIndex: '', // 装货地省index
    loadingAddressCIndex: '', // 装货地市index
    loadingAddressIndex: '', // 装货地区index

    unloadAddressPIndex: '', // 卸货地index
    unloadAddressCIndex: '', // 卸货地市index
    unloadAddressIndex: ''
  }

  constructor(private jsonApiService: JsonApiService) {}

  ngOnInit() {
    this.initDate().then(() => {
      this.load()
    })
    this.selectDate()
    this.selectCompany()
    this.getArea()
  }

  // 获取省市区，初始化级联选择器
  getArea() {
    this.jsonApiService.http('company/regionList.html', null).subscribe(res => {
      this.areaData = res.data
      for (let item of this.areaData) {
        if (item.level === 2) {
          this.provinceNameArr.push(item)
          this.provinceNameArr1.push(item)
        }
      }
    })
  }

  provinceChange(index) {
    this.cityNameArr = []
    this.areaSelected.loadingAddressCIndex = ''
    this.areaSelected.loadingAddressIndex = ''
    if (index !== 0 && !index) {
      return
    }
    const target = this.provinceNameArr[index]
    for (let item of this.areaData) {
      if (target.id === item.parentId) {
        this.cityNameArr.push(item)
      }
    }
  }

  //城市change回调事件
  cityChange(index) {
    this.townNameArr = []
    this.areaSelected.loadingAddressIndex = ''
    if (index !== 0 && !index) {
      return
    }
    const target = this.cityNameArr[index]
    for (let item of this.areaData) {
      if (target.id === item.parentId) {
        this.townNameArr.push(item)
      }
    }
  }

  provinceChange1(index) {
    this.cityNameArr1 = []
    this.areaSelected.unloadAddressCIndex = ''
    this.areaSelected.unloadAddressIndex = ''
    if (index !== 0 && !index) {
      return
    }
    const target = this.provinceNameArr1[index]
    for (let item of this.areaData) {
      if (target.id === item.parentId) {
        this.cityNameArr1.push(item)
      }
    }
  }
  //城市change回调事件
  cityChange1(index) {
    this.townNameArr1 = []
    this.areaSelected.unloadAddressIndex = ''
    if (index !== 0 && !index) {
      return
    }
    const target = this.cityNameArr1[index]
    for (let item of this.areaData) {
      if (target.id === item.parentId) {
        this.townNameArr1.push(item)
      }
    }
  }

  switchPosition() {
    // 交换省
    ;[this.areaSelected.loadingAddressPIndex, this.areaSelected.unloadAddressPIndex] = [
      this.areaSelected.unloadAddressPIndex,
      this.areaSelected.loadingAddressPIndex
    ]
    // 交换市
    ;[this.areaSelected.loadingAddressCIndex, this.areaSelected.unloadAddressCIndex] = [
      this.areaSelected.unloadAddressCIndex,
      this.areaSelected.loadingAddressCIndex
    ]
    // 交换区
    ;[this.areaSelected.loadingAddressIndex, this.areaSelected.unloadAddressIndex] = [
      this.areaSelected.unloadAddressIndex,
      this.areaSelected.loadingAddressIndex
    ]
    // 交换城市下拉选项
    ;[this.cityNameArr, this.cityNameArr1] = [this.cityNameArr1, this.cityNameArr]
    // 交换区下拉选项
    ;[this.townNameArr, this.townNameArr1] = [this.townNameArr1, this.townNameArr]
  }

  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker1')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = that.getTime(date)
              that.startTime = time
              $('#datetimepicker2').datetimepicker('setStartDate', time)
            })
          $('#datetimepicker2')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = that.getTime(date)
              that.endTime = time
              $('#datetimepicker1').datetimepicker('setEndDate', time)
            })
          resolve()
        })
      })
    })
  }

  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }

  load() {
    this.activeSelected = ''
    if (!this.getQueryParam(false)) return
    let reqdata = 'gridPager=' + JSON.stringify(this.getQueryParam(false))
    this.jsonApiService.http('transportJob/matlabOrderList.html', reqdata).subscribe(data => {
      if (data && data.exhibitDatas) {
        for (let item of data.exhibitDatas) {
          item.loadingTime = common.millisecond(item.loadingTime)
          item.unloadingTime = common.millisecond(item.unloadingTime)
          item.transportationTime = common.millisecond(item.transportationTime)
        }
        console.log(data.exhibitDatas)
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      }
    })
  }

  getTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  }

  exportTable() {
    if (!this.getQueryParam(true)) return
    const param = this.getQueryParam(true)
    common.exprotDataFile(param, 'gridPager', config.BaseURL + 'transportJob/matlabOrderList.html')
  }

  getQueryParam(isExport) {
    const timeCheck = common.correctTimeParams(this.queryForm.startTime, this.queryForm.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return false
    }
    const param = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        ...this.queryForm,
        sortTypeName: (this.queryForm.sortTypeNameArr || []).join(','),
        startTime: $('#datetimepicker1').val(),
        endTime: $('#datetimepicker2').val(),
        loadingAddress: '',
        unloadAddress: ''
      },
      isExport
    }
    if (this.areaSelected.loadingAddressPIndex) {
      const province = this.provinceNameArr[this.areaSelected.loadingAddressPIndex].areaName
      const city = this.areaSelected.loadingAddressCIndex
        ? this.cityNameArr[this.areaSelected.loadingAddressCIndex].areaName
        : ''
      const county = this.areaSelected.loadingAddressIndex
        ? this.townNameArr[this.areaSelected.loadingAddressIndex].areaName
        : ''
      param.parameters.loadingAddress = province + city + county
    }

    if (this.areaSelected.unloadAddressPIndex) {
      const province = this.provinceNameArr1[this.areaSelected.unloadAddressPIndex].areaName
      const city = this.areaSelected.unloadAddressCIndex
        ? this.cityNameArr1[this.areaSelected.unloadAddressCIndex].areaName
        : ''
      const county = this.areaSelected.unloadAddressIndex
        ? this.townNameArr1[this.areaSelected.unloadAddressIndex].areaName
        : ''
      param.parameters.unloadAddress = province + city + county
    }

    delete param.parameters.sortTypeNameArr
    return param
  }

  //删除所选时间
  del_date() {
    this.queryForm.startTime = ''
    this.queryForm.endTime = ''
    $('#datetimepicker1').val('').change()
    $('#datetimepicker2').val('').change()
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }

  selectDate() {
    if (!this.dateNumber) {
      return
    }
    let nowTime = new Date()
    this.queryForm.endTime = common.getTimeMmss(nowTime)
    nowTime.setDate(nowTime.getDate() - this.dateNumber)
    this.queryForm.startTime = common.getTimeMmss(nowTime)
  }

  companySelected(data) {
    this.queryForm.companyId = data.companyId
    this.queryForm.deviceId = data.deviceId
    this.queryForm.useTypeL2 = data.useTypeL2
  }

  refresh() {
    this.load()
  }

  table_search() {
    this.curPage = 1
    this.load()
  }

  index = 1
  selectCompany() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        let sortList = []
        if (this.index === 1) {
          sortList = [
            {
              text: '装载重量',
              id: 'weight'
            },
            {
              text: '卸货结束时间',
              id: 'unloadEndTime'
            },
            {
              text: '装载耗时',
              id: 'loadingTime'
            },
            {
              text: '卸载耗时',
              id: 'unloadingTime'
            }
          ]
          $('#sortSelect')
            .select2({
              language: 'zh-CN',
              placeholder: '请选择',
              allowClear: true,
              data: sortList //为Select添加数据
            })
            .on('select2:select', e => {
              this.queryForm.sortTypeNameArr = this.queryForm.sortTypeNameArr || []
              this.queryForm.sortTypeNameArr.push(e.params.data.id)
            })
            .on('select2:unselect', e => {
              const arrIndex = this.queryForm.sortTypeNameArr.indexOf(e.params.data.id)
              this.queryForm.sortTypeNameArr.splice(arrIndex, 1)
            })
          this.index++
        }
      })
    })
  }
}
